package com.ithinks.flow.common.utils.protocol.netty.echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @Description
 * @ClassName EchoClientHandler
 * @Author MR.LI
 * @date 2020.12.09 10:37
 */
public class EchoClientHandler  extends SimpleChannelInboundHandler<ByteBuf> {
    //客户端读取到数据后干什么
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf msg) throws Exception {
        System.out.println("Client accept:"+msg.toString(CharsetUtil.UTF_8));
    }
    //客户段被通知channel活跃以后，做事
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //往服务器写数据
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,netty",CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelReadComplete");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
